import { defineStore } from 'pinia'
import { setToken, removeToken } from '@/utils/auth'
import { fetchLogin } from '@/api/system/login'
import type { UserState } from './types'
import { useStorage } from '@vueuse/core'
import { StoreUserKey } from '@/config'
import { fetchUserInfo } from '@/api/system/user'
import { localRemove } from '@/utils'

const useUserStore = defineStore('user', {
  state: (): UserState => ({
    user: {},
    name: undefined,
    nickName: undefined,
    avatar: undefined,
    job: undefined,
    organization: undefined,
    location: undefined,
    email: undefined,
    introduction: undefined,
    personalWebsite: undefined,
    jobName: undefined,
    organizationName: undefined,
    locationName: undefined,
    phone: undefined,
    registrationDate: undefined,
    accountId: undefined,
    certification: undefined,
    roles: '',
  }),
  getters: {
    userInfo(state: UserState): UserState {
      return { ...state }
    },
  },

  actions: {
    // Reset user's information
    reset() {
      this.$reset()
    },

    update(partial: Partial<UserState>) {
      // @ts-ignore-next-line
      this.$patch(partial)
    },

    // 获取用户信息
    async getUserInfo() {
      return new Promise((resolve, reject) => {
        fetchUserInfo({ type: 'post' })
          .then((res: any) => {
            if (!res) {
              return reject('数据返回失败，请稍候在试')
            }
            this.user = res

            resolve(res)
          })
          .catch((error: any) => {
            reject(error)
          })
      })
    },

    async login(loginForm: any) {
      return new Promise((resolve, reject) => {
        fetchLogin({ params: loginForm, type: 'post' })
          .then((res) => {
            const { user, token } = res

            if (!user || !token) {
              reject('数据返回错误')

              return
            }

            this.user = user
            useStorage(StoreUserKey, res.user)
            setToken(token)
            resolve(res)
          })
          .catch((error: any) => {
            removeToken()
            reject(error)
          })
      })
    },

    // Logout
    async logout() {
      // await userLogout()

      localRemove(StoreUserKey)
      this.reset()
      // resetRouter()
      removeToken()
    },
  },
})

export default useUserStore
